"""对话仓库类"""

from typing import Optional, List
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import and_, or_, desc
from .base import BaseRepository
from app.models.database.conversation import Conversation
from app.models.database.message import Message
import uuid


class ConversationRepository(BaseRepository[Conversation]):
    """对话数据访问仓库"""
    
    def __init__(self, db: Session):
        super().__init__(db, Conversation)
    
    def create_conversation(self, conversation_id: Optional[str] = None, 
                          user_id: Optional[str] = None, title: Optional[str] = None) -> Conversation:
        """创建新对话"""
        return self.create(
            conversation_id=conversation_id or str(uuid.uuid4()),
            user_id=user_id,
            title=title or "新对话",
            message_count=0,
            is_active="true"
        )
    
    def get_by_conversation_id(self, conversation_id: str) -> Optional[Conversation]:
        """根据conversation_id获取对话"""
        return self.get_one_by_filter(conversation_id=conversation_id)
    
    def get_active_conversation(self, conversation_id: str) -> Optional[Conversation]:
        """获取活跃的对话"""
        return self.get_one_by_filter(conversation_id=conversation_id, is_active="true")
    
    def get_user_conversations(self, user_id: str, skip: int = 0, limit: int = 100) -> List[Conversation]:
        """获取用户的对话列表"""
        return (
            self.db.query(Conversation)
            .filter(Conversation.user_id == user_id)
            .order_by(desc(Conversation.updated_at))
            .offset(skip)
            .limit(limit)
            .all()
        )
    
    def get_user_active_conversations(self, user_id: str) -> List[Conversation]:
        """获取用户的活跃对话"""
        return self.get_by_filter(user_id=user_id, is_active="true")
    
    def get_conversation_with_messages(self, conversation_id: str) -> Optional[Conversation]:
        """获取包含消息的对话"""
        return (
            self.db.query(Conversation)
            .options(joinedload(Conversation.messages))
            .filter(Conversation.conversation_id == conversation_id)
            .first()
        )
    
    def get_recent_conversations(self, limit: int = 10) -> List[Conversation]:
        """获取最近的对话"""
        return (
            self.db.query(Conversation)
            .filter(Conversation.is_active == "true")
            .order_by(desc(Conversation.updated_at))
            .limit(limit)
            .all()
        )
    
    def search_conversations(self, query: str, user_id: Optional[str] = None, 
                           skip: int = 0, limit: int = 100) -> List[Conversation]:
        """搜索对话"""
        db_query = self.db.query(Conversation).filter(
            Conversation.title.ilike(f"%{query}%")
        )
        
        if user_id:
            db_query = db_query.filter(Conversation.user_id == user_id)
        
        return db_query.offset(skip).limit(limit).all()
    
    def update_conversation_title(self, conversation_id: str, title: str) -> Optional[Conversation]:
        """更新对话标题"""
        conversation = self.get_by_conversation_id(conversation_id)
        if conversation:
            return self.update(conversation, title=title)
        return None
    
    def increment_message_count(self, conversation_id: str) -> Optional[Conversation]:
        """增加消息计数"""
        conversation = self.get_by_conversation_id(conversation_id)
        if conversation:
            conversation.increment_message_count()
            conversation.update_last_message_time()
            self.db.commit()
            self.db.refresh(conversation)
            return conversation
        return None
    
    def activate_conversation(self, conversation_id: str) -> Optional[Conversation]:
        """激活对话"""
        conversation = self.get_by_conversation_id(conversation_id)
        if conversation:
            conversation.activate()
            self.db.commit()
            self.db.refresh(conversation)
            return conversation
        return None
    
    def deactivate_conversation(self, conversation_id: str) -> Optional[Conversation]:
        """停用对话"""
        conversation = self.get_by_conversation_id(conversation_id)
        if conversation:
            conversation.deactivate()
            self.db.commit()
            self.db.refresh(conversation)
            return conversation
        return None
    
    def get_conversation_stats(self, conversation_id: str) -> dict:
        """获取对话统计信息"""
        conversation = self.get_conversation_with_messages(conversation_id)
        if not conversation:
            return {}
        
        messages = conversation.messages
        user_messages = [m for m in messages if m.role == "user"]
        assistant_messages = [m for m in messages if m.role == "assistant"]
        
        # 计算反馈统计
        positive_feedback = len([m for m in messages if m.feedback == 1])
        negative_feedback = len([m for m in messages if m.feedback == -1])
        neutral_feedback = len([m for m in messages if m.feedback == 0])
        
        # 计算时间统计
        first_message_time = None
        last_message_time = None
        duration_minutes = None
        
        if messages:
            sorted_messages = sorted(messages, key=lambda x: x.created_at)
            first_message_time = sorted_messages[0].created_at
            last_message_time = sorted_messages[-1].created_at
            
            if first_message_time and last_message_time:
                duration = last_message_time - first_message_time
                duration_minutes = duration.total_seconds() / 60
        
        return {
            "conversation_id": conversation.conversation_id,
            "total_messages": len(messages),
            "user_messages": len(user_messages),
            "assistant_messages": len(assistant_messages),
            "positive_feedback_count": positive_feedback,
            "negative_feedback_count": negative_feedback,
            "neutral_feedback_count": neutral_feedback,
            "first_message_at": first_message_time.isoformat() if first_message_time else None,
            "last_message_at": last_message_time.isoformat() if last_message_time else None,
            "duration_minutes": duration_minutes,
            "title": conversation.title,
            "is_active": conversation.is_conversation_active(),
            "created_at": conversation.created_at.isoformat() if conversation.created_at else None
        }
    
    def get_user_conversation_count(self, user_id: str) -> int:
        """获取用户对话数量"""
        return self.count(user_id=user_id)
    
    def get_active_conversation_count(self, user_id: Optional[str] = None) -> int:
        """获取活跃对话数量"""
        filters = {"is_active": "true"}
        if user_id:
            filters["user_id"] = user_id
        return self.count(**filters)
    
    def cleanup_inactive_conversations(self, days: int = 30) -> int:
        """清理非活跃对话"""
        from datetime import datetime, timedelta
        cutoff_date = datetime.utcnow() - timedelta(days=days)
        
        # 找到长时间未活跃的对话
        inactive_conversations = (
            self.db.query(Conversation)
            .filter(
                and_(
                    Conversation.is_active == "true",
                    or_(
                        Conversation.last_message_at < cutoff_date,
                        Conversation.last_message_at.is_(None)
                    )
                )
            )
            .all()
        )
        
        # 停用这些对话
        count = 0
        for conversation in inactive_conversations:
            conversation.deactivate()
            count += 1
        
        if count > 0:
            self.db.commit()
        
        return count
